package com.hcms.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.hcms.admin.service.ICmsCateService;
import com.hcms.admin.service.ICmsPageService;
import com.hcms.mybatis.entity.CmsCate;
import com.hcms.mybatis.entity.CmsPage;
import com.hcms.mybatis.mapper.CmsPageMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章模块 服务实现类
 * </p>
 *
 * @author achenxw@126.com
 * @since 2023-03-31
 */
@Service
public class CmsPageServiceImpl extends ServiceImpl<CmsPageMapper, CmsPage> implements ICmsPageService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CmsPageMapper cmsPageMapper;

    @Autowired
    private ICmsCateService cmsCateService;

    @Override
    public List<CmsPage> getList(Long cateId, Integer status, Integer pageNum, Integer pageSize) {
        logger.info("Run getList(), pageNum={}, pageSize={}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize, "sort ASC, id DESC");

        LambdaQueryWrapper<CmsPage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(status != null, CmsPage::getStatus, status);
        //获取栏目子ID
        if (cateId != null) {
            List<CmsCate> cmsCates = cmsCateService.selectChildrenCate(cateId);
            List<Long> selectCateId = cmsCates.stream().map(CmsCate::getId).collect(Collectors.toList());
            selectCateId.add(cateId);
            queryWrapper.in(true, CmsPage::getCateId, selectCateId);
        }

        return cmsPageMapper.selectList(queryWrapper);
    }

    @Override
    public CmsPage getView(Long id) {
        logger.info("Run getView(), id={}", id);
        return cmsPageMapper.selectById(id);
    }

    @Override
    public int createItem(CmsPage entity) {
        logger.info("Run createItem()");
        entity.setCreateTime(new Date());
        return cmsPageMapper.insert(entity);
    }

    @Override
    public int updateItem(Long id, CmsPage entity) {
        logger.info("Run updateItem(), id={}", id);
        entity.setId(id);
        entity.setUpdateTime(new Date());
        return cmsPageMapper.updateById(entity);
    }

    @Override
    public int deleteItem(String ids) {
        logger.info("Run deleteItem(), ids={}", ids);
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        List<Long> collect = list.stream().map(Long::parseLong).collect(Collectors.toList());
        return cmsPageMapper.deleteBatchIds(collect);
    }
}
